import { useState } from 'react';
import { message } from 'antd';

const useUploadAvatar = ({ dispatch, user = {}, showMsg = false }) => {
    const [avatarData, setAvatarData] = useState({});
    const { avatarFile } = user;
    const hasAvatar = avatarFile && avatarFile.length;
    const existAvatar = hasAvatar ? avatarFile[0].url : '';

    const updateAvatar = () =>
        new Promise((resolve, reject) => {
            if (!avatarData.url) {
                resolve();
                return;
            }
            const { uploadResource } = avatarData;
            const array = [];
            array.push(uploadResource);
            dispatch({
                type: hasAvatar > 0 ? 'user/updateemployeeavatar' : 'user/uploademployeeavatar',
                payload: {
                    areaCode: '',
                    id: user.id,
                    mobile: '',
                    orgUserId: user.orgUserId,
                    resourceRelation: array
                },
                callback(res) {
                    if (res.code === 10000) {
                        if (showMsg) {
                            if (existAvatar) {
                                message.success('修改成功');
                            } else {
                                message.success('上传成功');
                            }
                        }

                        resolve();
                    } else {
                        if (showMsg) message.error(res.msg);
                        reject(res.msg);
                    }
                }
            });
        });

    const onFileChange = (showFileList, uploadResource) => {
        const uploadFile = [...showFileList].pop();
        if (uploadFile && uploadFile.status === 'done') {
            const reader = new FileReader();
            // 虽然没多大意义，还是加着吧
            setAvatarData({
                loading: true
            });
            reader.readAsDataURL([...showFileList].pop().originFileObj);
            reader.onload = () => {
                setAvatarData({
                    url: reader.result,
                    uploadResource,
                    loading: false
                });
            };
        }
    };

    return {
        onFileChange,
        updateAvatar,
        avatarData,
        hasAvatar,
        existAvatar
    };
};

export default useUploadAvatar;
